<template>
  <Dialog v-model="dialogVisible" :title="title" width="900px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="formData.planName" placeholder="请输入计划名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划编号" prop="planCode">
            <el-input v-model="formData.planCode" placeholder="自动生成" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="批次名称" prop="batchName">
            <el-input v-model="formData.batchName" placeholder="请输入批次名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划状态" prop="planStatus">
            <el-select v-model="formData.planStatus" placeholder="请选择状态">
              <el-option label="草稿" :value="0" />
              <el-option label="已提交" :value="1" />
              <el-option label="已审批" :value="2" />
              <el-option label="已发布" :value="3" />
              <el-option label="进行中" :value="4" />
              <el-option label="已完成" :value="5" />
              <el-option label="已取消" :value="6" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="计划描述" prop="planDescription">
        <el-input
          v-model="formData.planDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入计划描述"
        />
      </el-form-item>
      
      <!-- 时间安排 -->
      <el-divider content-position="left">时间安排</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报名开始日期" prop="registrationStartDate">
            <el-date-picker
              v-model="formData.registrationStartDate"
              type="date"
              placeholder="选择报名开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报名结束日期" prop="registrationEndDate">
            <el-date-picker
              v-model="formData.registrationEndDate"
              type="date"
              placeholder="选择报名结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价开始日期" prop="evaluationStartDate">
            <el-date-picker
              v-model="formData.evaluationStartDate"
              type="date"
              placeholder="选择评价开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价结束日期" prop="evaluationEndDate">
            <el-date-picker
              v-model="formData.evaluationEndDate"
              type="date"
              placeholder="选择评价结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 评价配置 -->
      <el-divider content-position="left">评价配置</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价职业" prop="professionId">
            <el-input
              v-model="formData.professionName"
              placeholder="请选择评价职业"
              readonly
              @click="openProfessionSelector"
            >
              <template #append>
                <el-button @click="openProfessionSelector" type="primary">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价方式" prop="evaluationMethod">
            <el-select v-model="formData.evaluationMethod" placeholder="请选择评价方式">
              <el-option label="考核评价" value="assessment" />
              <el-option label="岗位能力评价" value="competency" />
              <el-option label="考评结合" value="combined" />
              <el-option label="竞赛认定" value="competition" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价模板" prop="templateId">
            <el-select v-model="formData.templateId" placeholder="请选择评价模板" clearable>
              <el-option
                v-for="template in templateList"
                :key="template.id"
                :label="template.templateName"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 占位列 -->
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="适用等级" prop="applicableLevels">
            <el-input v-model="formData.applicableLevels" placeholder="请输入适用等级，逗号分隔" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大人数" prop="maxPeoplePerPlan">
            <el-input-number
              v-model="formData.maxPeoplePerPlan"
              :min="1"
              :max="9999"
              placeholder="最大人数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="考评员" prop="kpyrName">
            <el-select
              v-model="selectedEvaluators"
              multiple
              filterable
              placeholder="请选择考评员"
              style="width: 100%"
              @change="handleEvaluatorChange"
            >
              <el-option
                v-for="evaluator in evaluatorList"
                :key="evaluator.id"
                :label="evaluator.evaluatorName || evaluator.userName"
                :value="evaluator.evaluatorName || evaluator.userName"
              />
            </el-select>
            <div class="text-xs text-gray-500 mt-1">
              选择具有有效资质的考评员，可多选
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 联系信息 -->
      <el-divider content-position="left">联系信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 目标受众 -->
      <el-divider content-position="left">目标受众</el-divider>
      <el-form-item label="目标受众" prop="targetAudience">
        <el-radio-group v-model="formData.targetAudience">
          <el-radio value="all">全员</el-radio>
          <el-radio value="department">部门</el-radio>
          <el-radio value="position">岗位</el-radio>
          <el-radio value="manual">手动选择</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-row :gutter="20" v-if="formData.targetAudience === 'department'">
        <el-col :span="24">
          <el-form-item label="目标部门" prop="targetDepartments">
            <el-input v-model="formData.targetDepartments" placeholder="请输入目标部门ID，逗号分隔" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="formData.targetAudience === 'position'">
        <el-col :span="24">
          <el-form-item label="目标岗位" prop="targetPositions">
            <el-input v-model="formData.targetPositions" placeholder="请输入目标岗位ID，逗号分隔" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 职业选择器 -->
  <ProfessionSelector ref="professionSelectorRef" @select="handleProfessionSelect" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createPlan, updatePlan, getPlan } from '@/api/eval'
import { getValidEvaluatorList } from '@/api/eval/evaluator'
import { getPublishedTemplateList } from '@/api/eval/template'
import ProfessionSelector from './components/ProfessionSelector.vue'
import type { EvalProfessionVO } from '@/api/eval/profession'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const professionSelectorRef = ref()
const evaluatorList = ref([])
const selectedEvaluators = ref([])
const templateList = ref([])

const formData = ref({
  id: '',
  planName: '',
  planCode: '',
  batchName: '',
  professionId: 0,
  professionName: '',
  professionCode: '',
  applicableLevels: '',
  kpyrName: '',
  evaluationMethod: '',
  templateId: undefined,
  registrationStartDate: '',
  registrationEndDate: '',
  evaluationStartDate: '',
  evaluationEndDate: '',
  planStatus: 0,
  targetAudience: 'all',
  targetDepartments: '',
  targetPositions: '',
  maxPeoplePerPlan: 50,
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  planDescription: ''
})

const formRules = ref({
  planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  professionId: [{ required: true, message: '请选择评价职业', trigger: 'change' }],
  evaluationMethod: [{ required: true, message: '请选择评价方式', trigger: 'change' }],
  registrationStartDate: [{ required: true, message: '请选择报名开始日期', trigger: 'change' }],
  registrationEndDate: [{ required: true, message: '请选择报名结束日期', trigger: 'change' }],
  evaluationStartDate: [{ required: true, message: '请选择评价开始日期', trigger: 'change' }],
  evaluationEndDate: [{ required: true, message: '请选择评价结束日期', trigger: 'change' }],
  maxPeoplePerPlan: [{ required: true, message: '最大人数不能为空', trigger: 'blur' }]
})

const title = computed(() => formData.value.id ? '编辑评价计划' : '新增评价计划')

/** 生成计划编码 */
const generatePlanCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')

  return `PLAN-${year}${month}${day}-${hour}${minute}${second}`
}

/** 格式化日期数组为字符串 */
const formatDateArray = (dateArray: number[]) => {
  if (!Array.isArray(dateArray) || dateArray.length < 3) {
    return ''
  }
  const [year, month, day] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
}

/** 打开职业选择器 */
const openProfessionSelector = () => {
  professionSelectorRef.value?.open()
}

/** 处理职业选择 */
const handleProfessionSelect = (profession: EvalProfessionVO) => {
  formData.value.professionId = profession.id || 0
  formData.value.professionName = profession.professionName
  formData.value.professionCode = profession.professionCode

  // 自动填充适用等级
  if (profession.applicableLevels) {
    if (Array.isArray(profession.applicableLevels)) {
      formData.value.applicableLevels = profession.applicableLevels.join(',')
    } else {
      formData.value.applicableLevels = profession.applicableLevels
    }
  }
}

/** 处理考评员选择变化 */
const handleEvaluatorChange = (values: string[]) => {
  formData.value.kpyrName = values.join(',')
}

/** 加载考评员列表 */
const loadEvaluatorList = async () => {
  try {
    console.log('开始加载考评员列表...')
    const result = await getValidEvaluatorList()
    console.log('API返回结果:', result)
    // 根据实际返回的数据结构处理
    evaluatorList.value = Array.isArray(result) ? result : (result.data || [])
    console.log('处理后的考评员列表:', evaluatorList.value)
  } catch (error) {
    console.error('加载考评员列表失败:', error)
    evaluatorList.value = []
  }
}

/** 加载已发布的评价模板列表 */
const loadTemplateList = async () => {
  try {
    const result = await getPublishedTemplateList()
    templateList.value = Array.isArray(result) ? result : (result.data || [])
  } catch (error) {
    console.error('加载评价模板列表失败:', error)
    templateList.value = []
  }
}

const submitForm = async () => {
  const elForm = formRef.value
  if (!elForm) return

  try {
    const valid = await elForm.validate()
    if (!valid) return
  } catch (error) {
    console.log('表单验证失败:', error)
    return
  }

  formLoading.value = true
  try {
    // 使用JSON序列化和反序列化来创建一个干净的对象
    const rawData = JSON.parse(JSON.stringify(formData.value))

    // 确保必要字段有值
    const data: any = {
      planName: rawData.planName || '',
      planCode: rawData.planCode || generatePlanCode(),
      batchName: rawData.batchName || '',
      professionId: Number(rawData.professionId) || 0,
      professionName: rawData.professionName || '',
      professionCode: rawData.professionCode || '',
      applicableLevels: rawData.applicableLevels || '',
      kpyrName: rawData.kpyrName || '',
      evaluationMethod: rawData.evaluationMethod || '',
      registrationStartDate: rawData.registrationStartDate || '',
      registrationEndDate: rawData.registrationEndDate || '',
      evaluationStartDate: rawData.evaluationStartDate || '',
      evaluationEndDate: rawData.evaluationEndDate || '',
      planStatus: Number(rawData.planStatus) || 0,
      targetAudience: rawData.targetAudience || 'all',
      targetDepartments: rawData.targetDepartments || '',
      targetPositions: rawData.targetPositions || '',
      maxPeoplePerPlan: Number(rawData.maxPeoplePerPlan) || 50,
      contactPerson: rawData.contactPerson || '',
      contactPhone: rawData.contactPhone || '',
      contactEmail: rawData.contactEmail || '',
      planDescription: rawData.planDescription || ''
    }

    // 如果是编辑模式，添加id
    if (rawData.id) {
      data.id = rawData.id
    }

    // 移除空的id字段
    if (!data.id) {
      delete data.id
    }

    console.log('提交数据:', data)
    console.log('提交数据JSON:', JSON.stringify(data))

    if (data.id) {
      await updatePlan(data)
      ElMessage.success('修改成功')
    } else {
      await createPlan(data)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单数据')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: '',
    planName: '',
    planCode: '',
    batchName: '',
    professionId: 0,
    professionName: '',
    professionCode: '',
    applicableLevels: '',
    kpyrName: '',
    evaluationMethod: '',
    templateId: undefined,
    registrationStartDate: '',
    registrationEndDate: '',
    evaluationStartDate: '',
    evaluationEndDate: '',
    planStatus: 0,
    targetAudience: 'all',
    targetDepartments: '',
    targetPositions: '',
    maxPeoplePerPlan: 50,
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    planDescription: ''
  }
  selectedEvaluators.value = []

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()

  // 加载考评员列表和模板列表
  await loadEvaluatorList()
  await loadTemplateList()

  if (type === 'update' && id) {
    // 编辑模式：获取数据
    try {
      const data = await getPlan(id)
      console.log('获取到的编辑数据:', data)

      // 手动赋值，确保日期格式正确
      formData.value.id = data.id
      formData.value.planName = data.planName || ''
      formData.value.planCode = data.planCode || ''
      formData.value.batchName = data.batchName || ''
      formData.value.professionId = data.professionId || 0
      formData.value.professionName = data.professionName || ''
      formData.value.professionCode = data.professionCode || ''
      formData.value.applicableLevels = data.applicableLevels || ''
      formData.value.kpyrName = data.kpyrName || ''
      formData.value.evaluationMethod = data.evaluationMethod || ''
      formData.value.templateId = data.templateId || undefined

      // 设置选中的考评员
      if (data.kpyrName) {
        selectedEvaluators.value = data.kpyrName.split(',').filter(name => name.trim())
      }

      // 日期字段特殊处理 - 如果是数组格式则转换为字符串
      formData.value.registrationStartDate = Array.isArray(data.registrationStartDate)
        ? formatDateArray(data.registrationStartDate)
        : data.registrationStartDate || ''
      formData.value.registrationEndDate = Array.isArray(data.registrationEndDate)
        ? formatDateArray(data.registrationEndDate)
        : data.registrationEndDate || ''
      formData.value.evaluationStartDate = Array.isArray(data.evaluationStartDate)
        ? formatDateArray(data.evaluationStartDate)
        : data.evaluationStartDate || ''
      formData.value.evaluationEndDate = Array.isArray(data.evaluationEndDate)
        ? formatDateArray(data.evaluationEndDate)
        : data.evaluationEndDate || ''

      formData.value.planStatus = data.planStatus || 0
      formData.value.targetAudience = data.targetAudience || 'all'
      formData.value.targetDepartments = data.targetDepartments || ''
      formData.value.targetPositions = data.targetPositions || ''
      formData.value.maxPeoplePerPlan = data.maxPeoplePerPlan || 50
      formData.value.contactPerson = data.contactPerson || ''
      formData.value.contactPhone = data.contactPhone || ''
      formData.value.contactEmail = data.contactEmail || ''
      formData.value.planDescription = data.planDescription || ''

      console.log('赋值后的表单数据:', formData.value)
    } catch (error) {
      console.error('获取计划数据失败:', error)
      ElMessage.error('获取计划数据失败')
    }
  } else {
    // 新增模式：生成计划编号
    formData.value.planCode = generatePlanCode()
  }
}

defineExpose({ open })
</script>
